package com.loginTest;

import com.whenJay.HelloServlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;


public class LoginServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取信息
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String isAutoLogin = req.getParameter("isAutoLogin");
        //创建Session对象
        HttpSession session = null;
        //免密登录需创建cookie对象
        Cookie cookie = null;
        //判断用户账号和密码是否正确
        if(!"root".equals(username)||!"123".equals(password)){
            resp.sendRedirect("/?error=yes");
        }
        else{
            resp.setContentType("text/html;charset=UTF-8");
            resp.getWriter().println("欢迎您：" + username + "登录");
            session = req.getSession(true);
            session.setAttribute("username",username);
            //判断七天免登录
            if("on".equals(isAutoLogin)){
                cookie = new Cookie("username",username);
                cookie.setMaxAge(60*60*24*7);
                resp.addCookie(cookie);
            }
        }
    }
}
